from git import Repo
from pathlib import Path
from datetime import datetime
import statistics
import os
import shutil

# 仓库配置
gitee_link = "https://gitee.com/"
repo_url = "https://gitee.com/jeequan/jeepay"
repo_name = "jeepay"
repo_dir = Path(repo_name)

# 清理并克隆仓库
if repo_dir.exists():
    shutil.rmtree(repo_dir)
print(f"Cloning {repo_name} repository...")
repo = Repo.clone_from(repo_url, repo_name)
print(f"{repo_name} cloned successfully!")

# 准备Markdown报告
commits_link = f"{repo_url}/commits/master"
authors_link = f"{repo_url}/contributors"
branches_link = f"{repo_url}/branches"
branch_link = f"{repo_url}/tree/"

md = f"# {repo_name} Project Data Analysis\n\n"
md += "---\n\n"

# 获取提交历史
repo_commits = list(repo.iter_commits('--all'))
total_commits = len(repo_commits)

# 获取日期范围
first_commit = repo_commits[-1]
latest_commit = repo_commits[0]
start_date = first_commit.committed_datetime.strftime('%Y-%m-%d %H:%M:%S')
latest_date = latest_commit.committed_datetime.strftime('%Y-%m-%d %H:%M:%S')

md += f"**Start Date:** {start_date}\n\n"
md += f"**Latest Update:** {latest_date}\n\n"
md += f"[**Commits:** {total_commits}]({commits_link})\n\n"

# 处理分支
remote_branches = [ref.name.split('/')[-1] for ref in repo.remotes.origin.refs 
                  if 'HEAD' not in ref.name]
md += f"[**Branches:** {len(remote_branches)}]({branches_link})\n\n"

# 处理作者
author_data = {}
for commit in repo_commits:
    author = commit.author.name
    author_data[author] = author_data.get(author, 0) + 1

# 按提交数排序作者
sorted_authors = sorted(author_data.items(), key=lambda x: x[1], reverse=True)
total_authors = len(sorted_authors)
md += f"[**Authors:** {total_authors}]({authors_link})\n\n"

# 分支部分
md += "## Branches\n"
for branch in remote_branches:
    md += f"- [{branch}]({branch_link}{branch})\n"
md += "\n"

# 作者部分
md += "## Top 10 Authors\n"
for i, (author, count) in enumerate(sorted_authors[:10], 1):
    author_profile = author.replace(" ", "")
    md += f"{i}. [{author}]({gitee_link}{author_profile}): {count} commits\n"

if len(sorted_authors) < 10:
    md += "(本仓库贡献者不足10名)\n"
md += "\n"

# 提交统计
changes = []
for commit in repo_commits:
    changed_files = len(commit.stats.files)
    insertions = commit.stats.total['insertions']
    deletions = commit.stats.total['deletions']
    total_lines = insertions + deletions
    changes.append((changed_files, total_lines))

files_changed = [c[0] for c in changes]
lines_changed = [c[1] for c in changes]

md += "## Commit Stats\n"
md += f"**Average Lines Changed / Commit:** {sum(lines_changed)/total_commits:.1f}\n\n"
md += f"**Median Lines Changed / Commit:** {statistics.median(lines_changed)}\n\n"
md += f"**Average Files Changed / Commit:** {sum(files_changed)/total_commits:.1f}\n\n"
md += f"**Median Files Changed / Commit:** {statistics.median(files_changed)}\n"

# 保存报告
report_file = f"report-{repo_name}.md"
with open(report_file, 'w', encoding='utf-8') as f:
    f.write(md)
print(f"Report generated: {report_file}")